package com.jz.community.modulemine.rechargephone.ui.activity;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.rechargephone.adapter.FareDealAdapter;
import com.jz.community.modulemine.rechargephone.bean.FareDealBean;
import com.jz.community.modulemine.rechargephone.bean.FareSection;
import com.jz.community.modulemine.rechargephone.presenter.FareDealPresenter;
import com.jz.community.modulemine.rechargephone.ui.FareDealView;
import com.jz.community.modulemine.rechargephone.view.PhoneFareDialog;
import com.oushangfeng.pinnedsectionitemdecoration.PinnedHeaderItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class FareDealActivity extends BaseMvpActivity<FareDealView.View, FareDealPresenter> implements FareDealView.View, BaseQuickAdapter.RequestLoadMoreListener, OnRefreshListener {


    @BindView(R2.id.title_back)
    ImageButton titleBack;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.fare_deal_rv)
    RecyclerView fareDealRv;
    @BindView(R2.id.fare_deal_refresh)
    SmartRefreshLayout fareDealRefresh;

    private List<FareDealBean.ListBean> dealList = new ArrayList<>();
    private List<FareSection> fareSectionList = new ArrayList<>();
    private FareDealAdapter adapterDeal;

    private View noDataView;
    private View errorView;
    private View loadingView;

    private int page = 0;
    private int rows = 10;
    private int listSize = 0;

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_fare_deal;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected FareDealPresenter createPresenter() {
        return new FareDealPresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(titleToolbar);

        titleName.setText("充值记录");

        noDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) fareDealRv.getParent(), false);

        ImageView empty_iv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView empty_tv = (TextView) noDataView.findViewById(R.id.empty_tv);

        empty_iv.setImageResource(R.mipmap.empty_default);
        empty_tv.setText("暂无充值记录！");

        errorView = getLayoutInflater().inflate(R.layout.view_error, (ViewGroup) fareDealRv.getParent(), false);

        ImageView error_iv = (ImageView) errorView.findViewById(R.id.error_img);
        error_iv.setImageResource(R.mipmap.error_default);

        loadingView = getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) fareDealRv.getParent(), false);

        ImageView loading_iv = (ImageView) loadingView.findViewById(R.id.loading_img);
        GlideApp.with(mActivity)
                .asGif()
                .load(R.drawable.loading_default)
                .into(loading_iv);

        errorView.setOnClickListener(v -> {
            adapterDeal.setEmptyView(loadingView);
            mPresenter.initPhoneFare(page, rows);
        });

        //主-RecyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        fareDealRefresh.setOnRefreshListener(this);//刷新监听
        fareDealRefresh.setEnableLoadMore(false);
        fareDealRv.setHasFixedSize(true);
        fareDealRv.setFocusable(false);
        fareDealRv.setLayoutManager(layoutManager);

        fareDealRv.addItemDecoration(
                // 设置粘性标签对应的类型
                new PinnedHeaderItemDecoration.Builder(0x00000444)
                        // 设置分隔线资源ID
//                        .setDividerId(R.drawable.divider)
                        // 开启绘制分隔线，默认关闭
                        .enableDivider(false)
                        // 通过传入包括标签和其内部的子控件的ID设置其对应的点击事件
//                        .setClickIds(R.id.iv_more)
                        // 是否关闭标签点击事件，默认开启
//                        .disableHeaderClick(false)
                        // 设置标签和其内部的子控件的监听，若设置点击监听不为null，但是disableHeaderClick(true)的话，还是不会响应点击事件
//                        .setHeaderClickListener(clickAdapter)
                        .create());

        adapterDeal = new FareDealAdapter(R.layout.module_mine_item_fare_deal, R.layout.module_mine_item_money_title, fareSectionList);
//        adapterDeal.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);//加载动画
        adapterDeal.setOnLoadMoreListener(this, fareDealRv);
        fareDealRv.setAdapter(adapterDeal);

        adapterDeal.setOnItemClickListener((adapter, view, position) -> {
            if (!RxDataTool.isNullString(adapterDeal.getData().get(position).t.getRechargeStatus())) {
                if (RxDataTool.isInteger(adapterDeal.getData().get(position).t.getRechargeStatus())) {
                    int status = Integer.parseInt(adapterDeal.getData().get(position).t.getRechargeStatus());
                    if (status == 5) {
                        //点击出弹框
                        PhoneFareDialog dialog = new PhoneFareDialog(mActivity);
                        dialog.show();
                    }
                }

            }
        });
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        adapterDeal.setEmptyView(loadingView);
        mPresenter.initPhoneFare(page, rows);

    }


    @Override
    public void setPhoneFareData(FareDealBean entity) {
        freshEnd();
        //总页数
        dealList = entity.getList();
//        fareSectionList.clear();
        for (int i = 0; i < dealList.size(); i++) {
            String year = dealList.get(i).getYear();
            boolean isYear = false;
            List<FareSection> fareList = adapterDeal.getData();
            for (int k = 0; k < fareList.size(); k++) {
                if (fareList.get(k).isHeader) {

                    if (year.equals(fareList.get(k).header)) {
                        isYear = true;
                        break;
                    }
                }
            }
            if (!isYear) {
                fareSectionList.add(new FareSection(true, dealList.get(i).getYear()));
            }

            for (int j = 0; j < dealList.get(i).getData().size(); j++) {
                fareSectionList.add(new FareSection(dealList.get(i).getData().get(j)));
            }
        }

        if (dealList.size() <= 0) {
            //先设置空布局
            if (page == 0) {
                adapterDeal.replaceData(new ArrayList<>());
                adapterDeal.setEmptyView(noDataView);
                adapterDeal.notifyDataSetChanged();
            } else {
                adapterDeal.setEmptyView(noDataView);
                adapterDeal.notifyDataSetChanged();
            }
        } else {
            if (page == 0) {
                adapterDeal.setNewData(fareSectionList);
                //如果数据少 不显示已加载全部
                adapterDeal.disableLoadMoreIfNotFullPage();
            } else {
                adapterDeal.setNewData(fareSectionList);

            }
        }
        adapterDeal.loadMoreComplete();


    }

    @Override
    public void phoneFareFail(String msg) {
        adapterDeal.setEmptyView(errorView);
        adapterDeal.loadMoreFail();
    }

    public static List<FareDealBean.ListBean> removeDuplicate(List<FareDealBean.ListBean> list) {
        Set set = new LinkedHashSet<String>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }


    private void freshEnd() {
        fareDealRefresh.finishRefresh(200);
    }

    @OnClick(R2.id.title_back)
    public void onClick() {
        finish();
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (null != adapterDeal) {
            adapterDeal.setEnableLoadMore(false);
            adapterDeal.replaceData(new ArrayList<>());
            adapterDeal.setEmptyView(loadingView);
        }
        page = 0;
        mPresenter.initPhoneFare(page, rows);
        adapterDeal.setEnableLoadMore(true);

    }

    @Override
    public void onLoadMoreRequested() {
        fareDealRefresh.setEnableRefresh(false);
        final int size = dealList == null ? 0 : dealList.size();
        if (size == 0) {
            adapterDeal.loadMoreEnd();
            fareDealRefresh.setEnableRefresh(true);
        } else {
            page++;
            mPresenter.initPhoneFare(page, rows);
            fareDealRefresh.setEnableRefresh(true);

        }

    }


}
